package com.ifast.common.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;

import freemarker.template.Configuration;

public class CreateWordUtil {  
    
    private Configuration configuration = null;  
    @Value("${excelExportPath}")
    private  String excelExportPath;
      
    public CreateWordUtil(){  
        configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);  
        configuration.setDefaultEncoding("UTF-8");  
    }  
      
    public static void main(String[] args) {  
        CreateWordUtil test = new CreateWordUtil(); 
        Map<String,Object> dataMap=new HashMap<String,Object>();
        test.getData(dataMap);
        //test.createWord("题库模板.ftl", dataMap);
    }  
      
    public String createWord(String templateName, Map<String,Object> dataMap){  
    	configuration.setClassForTemplateLoading(this.getClass(), "/templates/ftl");//模板文件所在路径
        String path = ""; 
        File outFile = new File(excelExportPath + Math.random()*10000+".doc"); //导出文件
        try(Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)))){  
        	//获取模板文件    将填充数据填入模板文件并输出到目标文件 
        	configuration.getTemplate(templateName).process(dataMap, out); 
            path = outFile.getPath();
        } catch (Exception e) {  
            e.printStackTrace();  
        }
        return path;
    }  
  
    private void getData(Map<String, Object> dataMap) {  
        dataMap.put("title", "标题");  
//        dataMap.put("nian", "2016");  
//        dataMap.put("yue", "3");  
//        dataMap.put("ri", "6");   
//        dataMap.put("shenheren", "lc");  
          
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();  
        for (int i = 0; i < 10; i++) {  
            Map<String,Object> map = new HashMap<String,Object>();  
            map.put("xuehao", i);  
            map.put("neirong", "内容"+i);  
            list.add(map);  
        }  
          
          
        //dataMap.put("list", list);  
    }  
}
